<template>
  <div class="Image-page">
    <el-card>
      <div slot="header">
        <my-bread>素材管理</my-bread>
      </div>

      <!-- 单选按钮切换 -->
      <el-radio-group @change="changeCollect" v-model="reqParams.collect" size="small">
        <el-radio-button :label="false">全部</el-radio-button>
        <el-radio-button :label="true">收藏</el-radio-button>
      </el-radio-group>
      <el-button @click="openDialog" style="float: right" type="success" size="small">上传素材</el-button>
      <!-- 图片列表 -->
      <ul class="img-list">
        <li class="img-item" v-for="item in images" :key="item.id">
          <img :src="item.url" alt="">
          <p class="operation" v-if="!reqParams.collect">
            <span @click="toggleStatus(item)" class="el-icon-star-off" :class="{ 'active': item.is_collected}"></span>
            <span @click="deleteImage(item.id)" class="el-icon-delete"></span>
          </p>
        </li>
      </ul>
      <!-- 分页 -->
      <el-pagination
        background
        @current-change="changePage"
        layout="prev, pager, next"
        :current-page="reqParams.page"
        :page-size="reqParams.per_page"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 对话框 -->
    <el-dialog
      title="添加素材"
      :visible.sync="dialogVisible"
      :append-to-body="true"
      width="300px">
      <el-upload
        class="avatar-uploader"
        name="image"
        :action="imageBaseUrl"
        :headers="imageHeaders"
        :show-file-list="false"
        :on-success="handleUploadSuccess">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ImageOne',
  data () {
    return {
      reqParams: {
        // 表示的是全部还是收藏，false是全部
        collect: false,
        // 当前页
        page: 1,
        // 每页显示的条数
        per_page: 10
      },
      // 图片列表
      images: [],
      // 总条数
      total: 0,
      // 控制对话框显示和隐藏
      dialogVisible: false,
      // 预览路径
      imageUrl: '',
      // 文件上传的地址,需要是完整的地址
      imageBaseUrl: this.$axios.defaults.baseURL + '/mp/v1_0/user/images',
      // 上传图片的请求头
      imageHeaders: {
        Authorization: window.localStorage.getItem('token')
      }
    }
  },
  created () {
    this.getImage()
  },
  methods: {
    // 获取图片数据和分页数据
    async getImage () {
      const { data: { data } } = await this.$axios.get('/mp/v1_0/user/images', { params: this.reqParams })
      // console.log(data)
      this.images = data.results
      this.total = data.total_count
    },
    // 分页跳转
    changePage (changeData) {
      // console.log(changeData);
      // 把跳转之后的页数，赋值给当前的页码
      this.reqParams.page = changeData
      // 从新渲染页面
      this.getImage()
    },
    // 切换全部和收藏
    changeCollect () {
      this.reqParams.page = 1
      this.getImage()
    },
    // 收藏 和 取消收藏
    async toggleStatus (item) {
      try {
        const { data: { data } } = await this.$axios.put(`/mp/v1_0/user/images/${item.id}`, { collect: !item.is_collected })
        this.$message.success(data.collect ? '收藏成功' : '取消收藏成功')
        // 控制小星星的颜色
        item.is_collected = data.collect
      } catch (e) {
        this.$message.error(item.is_collected ? '收藏操作失败' : '取消收藏操作失败')
      }
    },
    // 删除图片
    deleteImage (id) {
      this.$confirm('此操作将永久删除该图片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.$axios.delete(`/mp/v1_0/user/images/${id}`)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getImage()
        } catch (e) {
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
        }
      }).catch(() => {

      })
    },
    // 控制对话框显示和隐藏
    openDialog () {
      // 点击之后把预览地址清空
      this.imageUrl = ''
      this.dialogVisible = true
    },
    // 点击上传图片
    handleUploadSuccess (results) {
      // console.log(results);

      // 预览图片
      this.imageUrl = results.data.url
      // 上传成功提示
      this.$message.success('上传素材成功!')
      window.setTimeout(() => {
        // 关闭对话框
        this.dialogVisible = false
        // 获取数据
        this.getImage()
      }, 2000)
    }
  }
}
</script>

<style scoped lang="less">
  .img-list {
    list-style: none;
    display: flex;
    flex-wrap: wrap;
    .img-item {
      position: relative;
      width: 180px;
      height: 180px;
      margin-right: 55px;
      margin-bottom: 20px;
      border: 1px dashed #ddd;
      img {
        width: 100%;
        height: 100%;
      }
      .operation {
        margin: 0;
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 30px;
        background: rgba(0, 0, 0, .3);
        display: flex;
        justify-content: space-around;
        align-items: center;
        span {
          color: #fff;
          &.active {
            color: red;
          }
        }
      }
    }
  }
</style>
